package AndroidDocSync.frontend;

import java.io.File;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


import docsync.*;


public class showDocList extends ListActivity {
	public static final String LOG_TAG = "showActionList";

	ArrayList<String> fileNameList = new ArrayList<String>();
	FileInterface[] localFiles = null;
	
	ExtensionMapper mapper = new ExtensionMapper();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.doclist);
		
		Log.v(LOG_TAG, "showActionList Activity started");
//		FileInterface[] localFiles = null;
		
//		FolderInterface folder = new AndroidFolder(this.getDir("docsync",
//				  Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE));

		FolderInterface folder = new AndroidFolder(new File("/sdcard/cmpe207/"));

		try {
			localFiles = folder.getFiles();
						
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.v(LOG_TAG, "exception caught when trying to get local files");
			finish();
			return;
		}
		
//		ArrayList<String> fileNameList = new ArrayList<String>();
		
		if (localFiles == null)
			Log.v(LOG_TAG, "no files found locally, may cause problems...");
		
		for (FileInterface f : localFiles)
		{
			fileNameList.add(f.getFilename());
		}
		
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, fileNameList);
		setListAdapter(arrayAdapter);
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.v(LOG_TAG, "id is - " + position);
		
		Intent intent = new Intent();
		
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		
		String Category = new String("android.intent.category.DEFAULT");
		
		AndroidFile file = (AndroidFile) localFiles[position];
		intent.setDataAndType(Uri.fromFile(file.getFile()), mapper.fromFilename(file.getFilename()));
		
		Log.v(LOG_TAG, "return from mapper - " + mapper.fromFilename(file.getFilename()));
		
		startActivity(intent);
	}
	
}
